package com.lanyun.aicorrectassistant.interceptor;


import com.lanyun.aicorrectassistant.constant.JwtClaimsConstant;
import com.lanyun.aicorrectassistant.context.LoginContextHolder;
import com.lanyun.aicorrectassistant.properties.JwtProperties;
import com.lanyun.aicorrectassistant.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/4/10
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    private static final String ADMIN = "/api-admin";

    private static final String APP = "/api-app";

    /**
     * admin端jwt令牌相关配置
     */
    public static String adminSecretKey = "lanyuntc";
    public static String adminTokenName = "Authorization";

    /**
     * app端用jwt令牌相关配置
     */
    public static String appSecretKey = "lanyuntc";
    public static String appTokenName = "AppAuthorization";

    /**
     * 需要忽略的请求
     */
    public static List<String> ignoreUris;

    static {
        if (ignoreUris == null) {
            ignoreUris = new LinkedList<>();
            ignoreUris.add("/api-admin/authUser/doLogin");
        }
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String adminToken = request.getHeader(adminTokenName);

        String requestURI = request.getRequestURI();

        // 放行白名单请求
        if (ignoreUris.contains(requestURI)) {
            return true;
        }

        Claims claims = null;

        try {
            if (requestURI.contains(ADMIN)) { // 处理管理端请求
                claims = JwtUtil.parseJWT(adminSecretKey, adminToken);
                if (Objects.isNull(claims)) {
                    throw new JwtException("JWT 身份校验失败");
                }
            } else if (requestURI.contains(APP)) { // 处理APP端请求
                claims = JwtUtil.parseJWT(appSecretKey, adminToken);
            }
        } catch (Exception e) {
            log.error("jwt.error:{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
        // 缓存用户上下文
        assert claims != null;
        this.cacheUserInfo(claims);
        return true;
    }

    private void cacheUserInfo(Claims claims) {
        if (claims == null) return;
        Object userId = claims.get(JwtClaimsConstant.USER_ID);
        if (Objects.nonNull(userId)) {
            LoginContextHolder.set(LoginContextHolder.LOGIN_USER_HEADER, userId);
        }
        Object role = claims.get(JwtClaimsConstant.USER_ROLE);
        if (Objects.nonNull(role)) {
            LoginContextHolder.set(LoginContextHolder.LOGIN_USER_ROLE_HEADER, role);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.remove();
    }
}
